package com.summer.NIO.udpService;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class DatagramChannelService {
	private DatagramChannel mServiceChannel;
	private Queue<Object> mMessageQueue = new ArrayBlockingQueue<Object>(1024);
	private List<InetSocketAddress> list = new ArrayList<InetSocketAddress>();
	
	public DatagramChannelService(int port) throws IOException{
		init(port);
	}
	
	private void init(int port) throws IOException{
		mServiceChannel = DatagramChannel.open();
		mServiceChannel.bind(new InetSocketAddress(port));
		
		MessageProcess messageProcessTask = new MessageProcess();
		messageProcessTask.start();
		
		messageReader();
	}
	
	protected void messageReader() throws IOException {
		ByteBuffer buf = ByteBuffer.allocate(1024);
		while(true){
			buf.clear();
			InetSocketAddress addr = (InetSocketAddress) mServiceChannel.receive(buf);
			if(!list.contains(addr)){
				list.add(addr);
			}
				
			buf.flip();
			
//			byte[] ipByte = new byte[InetAddress.getLocalHost().getAddress().length];
//			buf.get(ipByte, 0, ipByte.length);
			
//			byte[] portByte = new byte[4];
//			buf.get(portByte, 0, 4);
			
//			byte[] readByte = new byte[buf.limit()-ipByte.length-4];
			byte[] readByte = new byte[buf.limit()];
			buf.get(readByte, 0, readByte.length);
			
//			InetAddress cip = InetAddress.getByAddress(ipByte);
//			System.out.println("服务收到地址：" + cip.getHostAddress());
//			System.out.println("服务收到端口：" + Util.byteArrayToInt(portByte));
			System.out.println("服务收到地址addr：" + addr.getAddress());
			System.out.println("服务收到端口addr：" + addr.getPort());
			
//			mServiceChannel.connect(new InetSocketAddress(cip.getHostAddress(), Util.byteArrayToInt(portByte)));
//			mServiceChannel.send(ByteBuffer.wrap("我拿到了".getBytes()),new InetSocketAddress(cip.getHostAddress(), Util.byteArrayToInt(portByte)));
			mServiceChannel.send(ByteBuffer.wrap("我拿到了".getBytes()),addr);
			
			if(list.size()>=2){
				mServiceChannel.send(ByteBuffer.wrap(("A:"+list.get(1).getHostString()+":"+list.get(1).getPort()).getBytes()),list.get(0));
				mServiceChannel.send(ByteBuffer.wrap(("A:"+list.get(0).getHostString()+":"+list.get(0).getPort()).getBytes()),list.get(1));
			}
			mMessageQueue.add(new String(readByte));
		}
	}
	
	protected class  MessageProcess extends Thread{
		@Override
		public void run() {
			while(true){
				Object msg = mMessageQueue.poll();
				if(null != msg){
					System.out.println("服务收到消息："+msg.toString());
					
				}
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		DatagramChannelService service = new DatagramChannelService(9999);
	}
}
